package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.ApiOperation;
import org.example.exception.AppException;
import org.example.exception.AppExceptionCodeMsg;
import org.example.pojo.*;
import org.example.query.EmployeeQuery;
import org.example.service.IDepartmentService;
import org.example.service.IEmployeeService;
import org.example.service.ISchedulingService;
import org.example.service.impl.RoleServiceImpl;
import org.example.util.MD5Utils;
import org.example.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author peak
 * @since 2024-12-18
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController extends BaseController<Employee, EmployeeQuery> {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private ISchedulingService schedulingService;
    @Autowired
    private RoleServiceImpl roleServiceImpl;
    @Autowired
    private IDepartmentService departmentServiceImpl;

    @RequestMapping("/change/delmark")
    public ResultBean changeDelmark(@RequestBody Employee employee) throws AppException {

        if(employee == null ||
                employee.getId()==null ||
                employee.getId()==0 ||
                employee.getDelmark()==null) {
            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
        }
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<Employee>();
        updateWrapper.set("delmark", employee.getDelmark())
                .eq("id", employee.getId());
        //只是更新删除标记，逻辑删除
        Boolean result = employeeService.update(updateWrapper);

        return result?ResultBean.SUCCESS():ResultBean.ERROR("修改部门删除部门失败");
    }
    @ApiOperation("根据条件查询-不分页不联查")
    @PostMapping("/conditions")
    //首先先根据一个weekrule来查出一个排班的id
    //然后再根据一个名字来查询出一个员工id
    //之后将这些条件一起放到employeequery中在进行查询员工
    public ResultBean getByConditions(@RequestBody EmployeeQuery employeeQuery) throws AppException {
        System.out.println(employeeQuery.getScheduleIndex()+"  "+employeeQuery.getDeptmentId()+"  "+employeeQuery.getRegistLevelId()+"  "+employeeQuery.getRoleName());
        List<Scheduling> schedulingsList=schedulingService.list();
        schedulingsList.forEach(scheduling -> {
            System.out.println(scheduling.getWeekRule());
            char c=scheduling.getWeekRule().charAt(employeeQuery.getScheduleIndex());
            if(c=='1') {
                employeeQuery.setScheduleId(scheduling.getId());
            }
        });
        Role role=roleServiceImpl.getOne(new QueryWrapper<Role>().eq("name", employeeQuery.getRoleName()));
        employeeQuery.setRoleId(role.getId());

        List<Employee> list=employeeService.list(employeeQuery.getConditionWrapper());
        return ResultBean.SUCCESS(list);
    }
    @PutMapping("/resetpass/{id}")
    public ResultBean resetPass(@PathVariable("id") Integer empId) throws AppException {
        //这里应该是将密码拿出来进行加密之后再进行放回去
        UpdateWrapper<Employee> updateWrapper=new UpdateWrapper<>();
        String encrypt = MD5Utils.encrypt("111111");
        updateWrapper.set("password", encrypt)
                .eq("id", empId);
        boolean update = employeeService.update(updateWrapper);
        return update?ResultBean.SUCCESS():ResultBean.ERROR("重置密码失败，请重新重置");
    }
    @GetMapping("/getEmp/{EmployeeId}")
    public ResultBean getEmp(@PathVariable("EmployeeId") Integer empId) throws AppException {
        //联查
        MPJLambdaWrapper<Employee> wrapper=new MPJLambdaWrapper<>();
        wrapper.setAlias("e")
                .selectAll(Employee.class,"e")
                .selectAs(Department::getDeptName,"'department.deptName'")
                .selectAs(RegistLevel::getRegistName,"'registLevel.registName'")
                .selectAs(Role::getName,"'role.name'")
                .leftJoin(Department.class,"d",Department::getId,Employee::getDeptmentId)
                .leftJoin(RegistLevel.class,"rl",RegistLevel::getId,Employee::getRegistLevelId)
                .leftJoin(Role.class,"re",Role::getId,Employee::getRoleId)
                .eq("e.id",empId);
        Employee employee=employeeService.getOne(wrapper);
        return employee==null?ResultBean.ERROR("员工信息不存在"):ResultBean.SUCCESS(employee);
    }
    @PostMapping("/save")
    public ResultBean save(@RequestBody Employee employee) throws AppException {
        //这里要进行更新将其他的表的id进行填充

        //进行填充部门id
        QueryWrapper<Department> departmentQueryWrapper=new QueryWrapper<>();
        departmentQueryWrapper.eq("dept_name", employee.getDepartment().getDeptName());
        Department one = departmentServiceImpl.getOne(departmentQueryWrapper);
        employee.setDeptmentId(one.getId());
        //进行填充角色id
        QueryWrapper<Role> roleQueryWrapper=new QueryWrapper<>();
        roleQueryWrapper.eq("name",employee.getRole().getName());
        Role one1 = roleServiceImpl.getOne(roleQueryWrapper);
        employee.setRoleId(Math.toIntExact(one1.getId()));

        //接下来进行更新操作
        boolean save = employeeService.saveOrUpdate(employee);
        return save? ResultBean.SUCCESS():ResultBean.ERROR("添加员工信息失败");
    }
    @GetMapping("/batch1/{ids}")
    public ResultBean getBatchDel(@PathVariable("ids") List<Integer> list) throws Exception {
        //因为在前端的时候，直接变成19，21的形式了，在后端只需要进行转换即可
        boolean flg=employeeService.removeByIds(list);
        if(!flg){
            throw new AppException(AppExceptionCodeMsg.SAVE_FAIL);
        }
        return ResultBean.SUCCESS();
    }
}
